package com.hcss.core.common.mailmgt.service;


import java.util.List;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import com.hcss.core.common.mailmgt.model.MailModel;
import com.hcss.core.common.mailmgt.model.MyAuthenticator;
import com.hcss.core.common.mailmgt.model.SystemMailModel;
import com.hcss.core.mvc.BaseService;
import com.hcss.core.util.HtmlRegexpUtil;


/**
 * @ClassName: MailSender
 * @Description: TODO 邮件发送
 * @author lvfang
 * @date 2013-4-16 下午1:50:53
 * 
 */
@Service("mailSenderService")
public class MailSenderService extends BaseService{
	Logger logger  =  Logger.getLogger(getClass());
	@Autowired
	private TaskExecutor taskExecutor;// 注入Spring封装的异步执行器
	
	private JavaMailSenderImpl  mailSender;
	@Autowired
	private MailSetService mailSetService;
 	/** 
	* @Title: sendMail 邮件发送异步
	* @Description: TODO(这里用一句话描述这个方法的作用)
	* @param email
	* @throws 
	*/ 
	private void sendMail(MailModel email)  {
		if (email.getToAddress() == null || email.getToAddress().length == 0) {
			return;
		}
		sendMailByAsynchronousMode(email);
	}
	/** 
	* @Title: sendMail 邮件发送 同步
	* @Description: TODO(这里用一句话描述这个方法的作用)
	* @param email
	* @throws 
	*/ 
	private void sendSynchronizationMail(MailModel email)  {
		if (email.getToAddress() == null || email.getToAddress().length == 0) {
			return;
		}
		sendMailBySynchronizationMode(email);
	}
	/** 
	* @Title: sendMailBySynchronizationMode 
	* @Description: TODO 异步发送邮件
	* @param email
	* @throws 
	*/ 
	private void sendMailByAsynchronousMode(final MailModel email) {
		taskExecutor.execute(new Runnable() {
			public void run() {
				try {
					sendMailBySynchronizationMode(email);
				} catch (Exception e) {
					e.getStackTrace();
				}
			}
		});
	}

	/** 
	* @Title: sendMailBySynchronizationMode 
	* @Description: TODO 同步发送邮件
	* @param email
	* @throws 
	*/ 
	private void sendMailBySynchronizationMode(MailModel email){
		MimeMessage mime = mailSender.createMimeMessage();
		MimeMessageHelper helper;
		try {
			if(email.getFromAddress()==null || "".equals(email.getFromAddress())){
				String content = HtmlRegexpUtil.fiterHtmlTag(email.getContent(),"<br/>","\r\n");
				content = HtmlRegexpUtil.filterHtml(content);
				logger.warn("[Unsent Messages]："+content);
				return;
			}
			logger.info("Send mail start......");
			helper = new MimeMessageHelper(mime, true, "utf-8");
		
			helper.setFrom(email.getFromAddress());
			// 发件人
			helper.setTo(email.getToAddress());
			// 收件人
			helper.setBcc(email.getToAddress());
			// 暗送
			if (email.getCcAddress() != null && email.getCcAddress().length > 0) {
				helper.setCc(email.getCcAddress());// 抄送
			}
			// 回复到
			helper.setSubject(email.getSubject());
			// 邮件主题
			helper.setText(email.getContent(), true);
			// true表示设定html格式
			mailSender.send(mime);
			logger.info("MAIL SEND SUCCESS!!!");
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			logger.error("[MAIL SERVER ERROR]：", e);
		}
	}
	
	/**
	 * 批量发送邮件
	 * @param mails
	 * @return
	 */
	public int sendBatMail(List<MailModel> mails){
		SystemMailModel mailModel = null;
		try {
			mailModel = mailSetService.findSysModel();
			String mailServerHost = mailModel.getMailServerHost();
			String mailServerPort = mailModel.getMailServerPort();
			boolean validate = mailModel.isValidate();
			String mailAdminAddress = mailModel.getMailAdminAddress();
			String mailAdminPwd = mailModel.getMailAdminPwd();
			mailSender = new JavaMailSenderImpl();
			mailSender.setHost(mailModel.getMailServerHost());
			mailSender.setUsername(mailAdminAddress.split("@")[0]);
			mailSender.setPassword(mailAdminPwd);
			Properties p = new Properties();
			p.put("mail.smtp.host", mailServerHost);
			p.put("mail.smtp.port", mailServerPort);
			p.put("mail.smtp.auth", "true");
			// 如果需要身份认证，则创建一个密码验证器   
			mailSender.setSession(Session.getDefaultInstance(p,new MyAuthenticator(mailAdminAddress, mailAdminPwd)));
			mailSender.setJavaMailProperties(p);
			if(mailModel.getMailServerPort() != null){
				mailSender.setPort(new Integer(mailServerPort));
			}
			mailSender.setDefaultEncoding("UTF-8");
			
			
			for(MailModel mail : mails){
				mail.setMailServerHost(mailServerHost);
				mail.setMailServerPort(mailServerPort);
				mail.setValidate(validate);
				mail.setUserName(mailAdminAddress);
				mail.setPassword(mailAdminPwd);// 您的邮箱密码
				mail.setFromAddress(mailAdminAddress);
				this.sendMail(mail);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("[SystemSet Error]：", e);
		}
		return mails.size();
	}

	/**
	 * @Title: sendMuptMail
	 * @Description: TODO 邮件发送 String
	 * @param mailSubject
	 *            主题 String
	 * @param mailCotent
	 *            内容 String
	 * @param toAddress
	 *            收件人 String []
	 * @param ccAddress
	 *            抄送人 String []
	 * @throws Exception
	 * @throws
	 */
	public int sendMuptMail(String mailSubject, String mailCotent,
			String[] toAddress, String[] ccAddress)  {
		SystemMailModel mailModel = null;
		try {
			mailModel = mailSetService.findSysModel();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("[SystemSet Error]：", e);
		}
		MailModel mailInfo = new MailModel();
		mailInfo.setMailServerHost(mailModel.getMailServerHost());
		mailInfo.setMailServerPort(mailModel.getMailServerPort());
		mailInfo.setValidate(mailModel.isValidate());
		mailInfo.setUserName(mailModel.getMailAdminAddress());
		mailInfo.setPassword(mailModel.getMailAdminPwd());// 您的邮箱密码
		mailInfo.setFromAddress(mailModel.getMailAdminAddress());
		mailInfo.setToAddress(toAddress);
		mailInfo.setCcAddress(ccAddress);
		mailInfo.setSubject(mailSubject);
		mailInfo.setContent(mailCotent);
		
		mailSender = new JavaMailSenderImpl();
		mailSender.setHost(mailModel.getMailServerHost());
		mailSender.setUsername(mailModel.getMailAdminAddress().split("@")[0]);
		mailSender.setPassword(mailModel.getMailAdminPwd());
		Properties pro = mailInfo.getProperties();   
		MyAuthenticator authenticator = null;    
		if (mailInfo.isValidate()) {    
      	// 如果需要身份认证，则创建一个密码验证器    
			authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());    
		}
		mailSender.setSession(Session.getDefaultInstance(pro,authenticator));
		mailSender.setJavaMailProperties(pro);
		if(mailModel.getMailServerPort() != null){
			mailSender.setPort(new Integer(mailModel.getMailServerPort()));
		}
		mailSender.setDefaultEncoding("UTF-8");
		try {
			this.sendMail(mailInfo);
			return 1;
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("[MAIL SERVER ERROR]：", e);
		}
		return 0;
	}
	/**
	 * @Title: sendMuptMail
	 * @Description: TODO 邮件发送 String 同步
	 * @param mailSubject
	 *            主题 String
	 * @param mailCotent
	 *            内容 String
	 * @param toAddress
	 *            收件人 String []
	 * @param ccAddress
	 *            抄送人 String []
	 * @throws Exception
	 * @throws
	 */
	public int sendSynchronizationMail(String mailSubject, String mailCotent,
			String[] toAddress, String[] ccAddress)  {
		SystemMailModel mailModel = null;
		try {
			mailModel = mailSetService.findSysModel();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("[SystemSet Error]：", e);
		}
		MailModel mailInfo = new MailModel();
		mailInfo.setMailServerHost(mailModel.getMailServerHost());
		mailInfo.setMailServerPort(mailModel.getMailServerPort());
		mailInfo.setValidate(mailModel.isValidate());
		mailInfo.setUserName(mailModel.getMailAdminAddress());
		mailInfo.setPassword(mailModel.getMailAdminPwd());// 您的邮箱密码
		mailInfo.setFromAddress(mailModel.getMailAdminAddress());
		mailInfo.setToAddress(toAddress);
		mailInfo.setCcAddress(ccAddress);
		mailInfo.setSubject(mailSubject);
		mailInfo.setContent(mailCotent);
		
		mailSender = new JavaMailSenderImpl();
		mailSender.setHost(mailModel.getMailServerHost());
		mailSender.setUsername(mailModel.getMailAdminAddress().split("@")[0]);
		mailSender.setPassword(mailModel.getMailAdminPwd());
		Properties pro = mailInfo.getProperties();   
		MyAuthenticator authenticator = null;    
		if (mailInfo.isValidate()) {    
      	// 如果需要身份认证，则创建一个密码验证器    
			authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());    
		}
		mailSender.setSession(Session.getDefaultInstance(pro,authenticator));
		mailSender.setJavaMailProperties(pro);
		if(mailModel.getMailServerPort() != null){
			mailSender.setPort(new Integer(mailModel.getMailServerPort()));
		}
		mailSender.setDefaultEncoding("UTF-8");
		
		try {
			this.sendSynchronizationMail(mailInfo);
			return 1;
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("[MAIL SERVER ERROR]：", e);
		}
		return 0;
	}
}
